<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" label-width="100px" v-loading="formLoading">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="formData.categoryName" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="分类描述">
        <el-input
          :rows="5"
          type="textarea"
          v-model="formData.description"
          placeholder="请输入商品简介"
        />
      </el-form-item>
      <el-form-item label="分类图片" prop="picUrl">
        <el-upload
          class="avatar-uploader"
          v-model:file-list="fileList"
          action=""
          list-type="picture-card"
          :limit="1"
          accept="image/*"
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handlePicUplad"
          :on-exceed="handleExceed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="排序" prop="sortNo">
        <el-input v-model="formData.sortNo" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="0">启用</el-radio>
          <el-radio :label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as ProductCategoryApi from '@/mock/client-mall/product/category/index.ts'
import { Plus } from '@element-plus/icons-vue'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const fileList = ref([]) // 回显文件上传列表
const uploadFile = ref([]) // 上传的文件
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  parentId: undefined,
  categoryName: undefined,
  description: undefined,
  picUrl: undefined,
  sortNo: undefined,
  status: undefined
})
const formRules = reactive({
  parentId: [{ required: true, message: '父id不能为空', trigger: 'blur' }],
  categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '分类描述不能为空', trigger: 'blur' }],
  picUrl: [{ required: true, message: '分类图片不能为空', trigger: 'blur' }],
  sortNo: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  uploadFile.value = []
  fileList.value = []
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductCategoryApi.getCategory(id)
      // 设置图片回显
      fileList.value = [
        {
          name: '分类图片',
          url: formData.value.picUrl
        }
      ]
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    submitFileUpload() // 提交文件上传
    const data = formData.value as unknown as ProductCategoryApi.ProductCategoryVO
    if (formType.value === 'create') {
      await ProductCategoryApi.createCategory(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProductCategoryApi.updateCategory(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    parentId: undefined,
    categoryName: undefined,
    description: undefined,
    picUrl: undefined,
    sortNo: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}

// 图片文件上传
const handlePicUplad = (file, fileList) => {
  if (file.size / 1024 / 1024 > 1) {
    ElMessage.error('文件最大不能超过 2MB!')
    fileList.splice(fileList.length - 1, 1)
    return
  }
  uploadFile.value = fileList
}

// 文件超出个数限制
const handleExceed = () => {
  ElMessage.warning('超出文件个数限制')
}

const submitFileUpload = async () => {
  // 上传图片,替换链接
  if (uploadFile.value.length > 0) {
    await ProductCategoryApi.deleteUploadFile(formData.value.picUrl) // 删除原本的旧图片
    // 上传图片， 替换链接
    const fd = new FormData()
    fd.append('file', uploadFile.value[0])
    const res = await ProductCategoryApi.uploadFile(fd)
    formData.value.picUrl = res.url
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>
